/*
 * LinkMonitor.java
 * 
 * last update: 16.01.2010 by Stefan Saru
 * 
 * author:	Alec(panovici@elcom.pub.ro)
 * 
 * Obs:
 */
package engine;

/**
 * Used for value propagation
 * when strength are not a point
 * (i.e.) a non-strength aware MContAssignMonitor.
 * Used internally by std. gates for i/o replication.
 */
class LinkMonitor implements Monitor, Executable{

	LeftValue lValue;
	Expression rValue;
	BitVector prevValue, curValue;

	boolean active;
	int length;

	LinkMonitor (LeftValue lValue,
			Expression rValue) {
		active = false;
		this.lValue = lValue;
		this.rValue = rValue;
		length = rValue.length;
		curValue = prevValue = BitVector.bX();
		rValue.addMonitor(this);
	}

	/**
	 * Note:
	 * If triggered multiple times per time-unit, it will execute
	 * only once, assigning the last update value.
	 */
	public synchronized void trigger() throws InterpretTimeException {
		curValue = rValue.evaluate().getBits();

		xConsole.debug("LinkMonitor.trigger: curValue is: " + curValue);
		if (!curValue.equals(prevValue)) {
			prevValue = curValue;
			if (!active) { //group as many modifications as
				//we can per single execution 
				xConsole.trace("triggering continuous assignement: " +
						lValue + " <<< " + curValue);
				Time.addFinisher(0, new GenericInstruction(this));
				active = true;
			}
		}
	}


	public void execute ()
	throws InterpretTimeException
	{
		xConsole.trace(toString() +  " <<< " + curValue);
		lValue.assign(curValue);
		active = false;
	}

	public String toString() {
		return lValue + "<=" + rValue;
	}
}
